package com.ruoyi.api.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ruoyi.api.cache.ICacheService;
import com.ruoyi.api.util.JWTUtil;
import com.ruoyi.api.util.SpringApplicationContextUtil;
import com.ruoyi.framework.web.exception.app.AppAuthException;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.service.IUserService;

import io.jsonwebtoken.Claims;

public class JwtInterceptor extends HandlerInterceptorAdapter {
	 
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception{
		String authHeader = request.getHeader("Authorization");
		if (authHeader == null || !authHeader.startsWith("Bearer:")) {
			throw new AppAuthException("auth-00001", "用户未授权");
		}
		String token = authHeader.substring(7);
		Claims claims = JWTUtil.parseToken(token);
		String subject = claims.getSubject();
		ICacheService cacheService = (ICacheService)SpringApplicationContextUtil.getBean(ICacheService.class);
		String currentUserToken = (String) cacheService.get("ry-user-token", subject);
		if(!token.equals(currentUserToken)){
			throw new AppAuthException("auth-00003","用户已被踢出，请重新登录");
		}
        try {
            boolean reAuth = false;
            if(JWTUtil.validateTokenEffective( token.toString() )) {//过期失效
                reAuth = true;
            }
            if(reAuth){
            	//过期了啦
            	throw new AppAuthException("auth-00002", "用户授权已过期");
            }else {
            }
        } catch (Exception e) {
        	throw new AppAuthException("auth-00001", "用户未授权");
        }
        Integer currentUserId = (Integer) cacheService.get("ry-user-id", subject);
        IUserService userService = (IUserService)SpringApplicationContextUtil.getBean(IUserService.class);
        User user = userService.selectUserById(currentUserId);
		request.setAttribute("userName",claims.getSubject());
		request.setAttribute("user",user);
		request.setAttribute("userId",currentUserId);
		
		return true;
	}
	
}